<script lang="ts" setup>
import type { BaseinfoDemandApi } from '#/api/csyt/baseinfodemand';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  getBaseinfoDemand,
  updateBaseinfoDemandStatus,
} from '#/api/csyt/baseinfodemand';
import { $t } from '#/locales';

import { demandeStatusFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<BaseinfoDemandApi.BaseinfoDemand>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['产品信息'])
    : $t('ui.actionTitle.create', ['产品信息']);
});

const [DemandStatusForm, demandStatusFormApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: demandeStatusFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await demandStatusFormApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = await demandStatusFormApi.getValues();
    try {
      // 提交修改
      await updateBaseinfoDemandStatus({
        id: data.id, // 序号
        demandName: data.demandName, // 需求名称
        demandNo: data.demandNo, // 需求编码
        companyName: data.companyName, // 企业名称
        demandStatus: data.demandStatus, // 需求状态
        onlyDemand: true,
      });
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    // 加载数据
    let data = modalApi.getData<BaseinfoDemandApi.BaseinfoDemand>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await getBaseinfoDemand(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    // 设置到 values
    formData.value = data;
    await demandStatusFormApi.setValues(formData.value);
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <DemandStatusForm class="mx-4" />
  </Modal>
</template>
